<?php
// +----------------------------------------------------------------------
// | ScrollPHP
// +----------------------------------------------------------------------
// | @copyright Copyright (c) 2014 PhpStorm All rights reserved.
// +----------------------------------------------------------------------
// | @license Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author LIZHEN
// +----------------------------------------------------------------------
// | @version 0.0.1 (2014-09-04)
// +----------------------------------------------------------------------
// | @info $Id: Route.class.php 2766 14-9-5 上午9:57 LIZHEN $
// +----------------------------------------------------------------------
// | @package

class Route {
		
    public static function run() {
    	//$config = include APP_PATH . '/config.php';
		$controller = empty($_GET['c']) ? C('defaultController') : ucfirst(trim($_GET['c'])); //设置了默认的控制器
		$action = empty($_GET['a']) ? C('defaultAction') : strtolower(trim($_GET['a'])); //设置了默认的Action
		$controllerBasePath = MODULES_PATH . '/Controllers/';
		$controllerFilePath = $controllerBasePath . $controller . 'Controller.class.php';
        tp_include(FRAMEWORK_PATH.'/Exception/NoClassException.class.php');
        //C("url=>baseurl",self::_getBaseUrl());
        Path::setBasePath(self::_getBaseUrl());
        Path::setController(C('defaultController'));
        Path::setAction(C('defaultAction'));
		if(is_file($controllerFilePath)) {
			include $controllerFilePath;
			$controllerName = $controller . 'Controller';

			if(class_exists($controllerName)) {
				$controllerHandler = new $controllerName();
				if(method_exists($controllerHandler, $action)) {
					$controllerHandler->$action();
				} else {
                    throw new NoClassException(NoClassException::NONE_EXISTS_METHOD);
				}
			} else {
                throw new NoClassException($controllerName, NoClassException::NONE_EXISTS_CLASS);
			}
		} else {
			throw new NoClassException($controllerFilePath, NoClassException::NONE_EXISTS_FILE);
		}
	}

    protected static function _getBaseUrl() {
        $url = $_SERVER['REQUEST_URI'];
        $baseUrl = '';
        if(false !== strpos($url,'.php')) {
            $baseUrl = $_SERVER['HTTP_HOST'].substr($url,0,(strpos($url,'.php')+4));
        } elseif(false === C('url=>rewrite')) {
            //解决没有rewrite,但是没有.php这种情况
            $baseUrl = $_SERVER['HTTP_HOST'].$url.'index.php';
        } else {
            $baseUrl = $_SERVER['HTTP_HOST'];
        }
        return $baseUrl;
    }

}